package com.beizhen.demo.utils;

import com.aliyun.oss.OSSClient;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.net.URL;
import java.util.Date;

public class Fileupload {
    /**
     *
     把文件保存到阿里云OSS，返回路径保存到数据库
     */
    public static String getUrl(MultipartFile fileupload) throws IOException {
        String endpoint = "oss-cn-beijing.aliyuncs.com";
        String accessKeyId = "LTAI4FxvwprbZ98Eek4vSJKq";
        String accessKeySecret = "sQBUOFggb7ub1LzQ3BWdSbS1ym1VPz";
        // 创建OSSClient实例
        OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);

        // 文件桶
        String bucketName = "ycvideonetwork";
        // 该桶中的文件key
        String dateString = fileupload.getOriginalFilename();
        // 上传文件
        ossClient.putObject(bucketName, dateString, new ByteArrayInputStream(fileupload.getBytes()));

        // 设置URL过期时间为100年，默认这里是int型，转换为long型即可
        Date expiration = new Date(new Date().getTime() + 3600l * 1000 * 24 * 365 * 100);
        // 生成URL
        URL url = ossClient.generatePresignedUrl(bucketName, dateString, expiration);
        ossClient.shutdown();
        return url.toString();
    }

}
